package com.qky.dao.baseDao;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import javax.persistence.Table;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.qky.dao.utilDao.CurrentSessionDao;
import com.qky.util.MapUtil;
import com.qky.util.PageUtil;

@Repository
public class BaseDao<E> extends CurrentSessionDao{
	/**
	 * 
	 * @param pageIndex 当前页
	 * @param pageSize	每页数量
	 * @param entity	实体类名称
	 * @return  一个包含实体类对象集合，总数量。。。
	 */
	@SuppressWarnings("unchecked")
	public final PageUtil getUserListByPageUtil(int pageIndex, int pageSize,Class<E> t) {
		int beginRow=(pageIndex-1)*pageSize;
		List<E> plist=currentSession()
				.createCriteria(t)
				.setFirstResult(beginRow)
				.setMaxResults(pageSize).list();
		String tableName=t.getAnnotation(Table.class).name();
		//String tableName=entity.getClass().getAnnotation(Entity.class).name();
		Object count=currentSession().createSQLQuery("select count(0) from "+tableName).uniqueResult();
		PageUtil pageUtil=new PageUtil(pageIndex,pageSize,Integer.valueOf(count.toString()));
		pageUtil.setPlist(plist);
		return pageUtil;
	}
	
	@SuppressWarnings("unchecked")
	public E getUserByLogin(E e){
		Map<String, String> eMap = null;
		try {
			eMap = MapUtil.EntityTranMap(e);
		} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException
				| IntrospectionException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		Criteria criteria=currentSession().createCriteria(e.getClass());
		criteria.add(Restrictions.allEq(eMap));
		return e=(E) criteria.uniqueResult();
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	/*public List getEntityPageBySearchMap(Class<E> e,Map<String,String> queryMap,int pageIndex,int pageSize) {
		Criteria criteria=currentSession().createCriteria(e);
		for (Entry<String,String> entry : queryMap.entrySet()) {//遍历query 条件
            //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
            String key =  entry.getKey() ;
            String valueString = entry.getValue();
            int id;
            if (valueString.split(",").length>1) {
            	String [] valuesArray;
            	valuesArray=valueString.split(",");
            	if (key.equalsIgnoreCase("id")) {
            		List<Integer> idList=new ArrayList<Integer>();
            		for (String string : valuesArray) {
            			id = Integer.parseInt(string);
            			idList.add(id);
            		}
            		Integer [] idsArray=idList.toArray(new Integer [idList.size()]);
            		criteria.add(Restrictions.in(key,idsArray));
            	}else if(key.equalsIgnoreCase("state")){
            		criteria.add(Restrictions.in(key,valuesArray));
            	}else {
            		Disjunction dis=Restrictions.disjunction();  
            		for (String string : valuesArray) {
            			dis.add(Restrictions.like(key,"%"+string+"%", MatchMode.ANYWHERE));
            		}
            		criteria.add(dis);
            	}
            }else {
            	if (key.equalsIgnoreCase("id")) {
            		id = Integer.parseInt(valueString);
            		criteria.add(Restrictions.idEq(id));
            	}else if(key.equalsIgnoreCase("ruleType")){
            		criteria.add(Restrictions.eq(key,valueString));
            	}else if(key.equalsIgnoreCase("state")){
            		criteria.add(Restrictions.eq(key,valueString));
            	}else{
            		criteria.add(Restrictions.like(key,"%"+valueString+"%"));
            	}
            }
		}
		List list=new ArrayList();
		//增加去重
        List tList=criteria.list();
        int totalRow=tList.size();
        //反序list
        Collections.reverse(tList);
        int newPageSize=pageSize;
        //如果当前页大于总条数除以当前每页数量
        if (pageIndex>totalRow/pageSize) {
            newPageSize=totalRow%pageSize;
        }
        if (beginRow+newPageSize>totalRow) {
            pageIndex=1;
            beginRow=0;
        }
        List pList=tList.subList(beginRow,beginRow+newPageSize);
        PageUtil pageUtil=new PageUtil(pageIndex, pageSize,totalRow, pList);
        return pageUtil;
		return list;
	}*/
	public final E add(E e){
		currentSession().save(e);
		return  e;
	}
	@SuppressWarnings("unchecked")
	public final E getById(Class<E> t,int id) {
		return (E)currentSession().get(t,id);
	}
	/*
	public final void update(T t){
		currentSession().update(t);
	}

	public final void merge(T t){
		currentSession().merge(t);
	}
	public final void delete(T t) {
		currentSession().delete(t);
	}

	public final T get(Class<E> entityClass, Serializable id) {
		T ret = (T) currentSession().get(entityClass, id);
		return ret;
	}
	public final void deleteById(Serializable id){
		T ret = this.get(this.getEntityClass(), id);
		if (ret != null){
			delete(ret);
		}
	}
	
//	@Override
//	public final List<E> findAll() throws Exception {
//		String hql = "from "+this.getEntityClassName();
//		return this.queryForList(hql, null).getResultList();
//		
//	}
//	@Override
//	public final PageList<E> findAll(PageBean pageBean) throws Exception {
//		String hql = "from "+this.getEntityClassName();
//		return (PageList<E>)this.queryForList(hql, pageBean);
//		
//	}
	@SuppressWarnings("unchecked")
	public final T findById(Serializable id){
		return (T)currentSession().get(getEntityClassName(), id);
		
	}
//	public final T findForObject(final T entity){
//		PageList<E> pageList = findForList(entity, null);
//		if(pageList != null && pageList.getResultList() != null && !pageList.getResultList().isEmpty()){
//			return pageList.get(0);
//		}
//		return null;
//	}
//	@SuppressWarnings("unchecked")
//	public final PageList<E> findForList(final T entity, final PageBean pageBean){
//		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(entity.getClass()).add(Example.create(entity));
//		List<?> list = null;
//		if(!PageBean.isEmpty(pageBean)) {
//			list = hibernateTemplate.findByCriteria(detachedCriteria, pageBean.getLimit(), pageBean.getOffset());
//			Criteria criteria = detachedCriteria.getExecutableCriteria(hibernateTemplate.getSessionFactory().getCurrentSession());
//			Long totalCount = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
//			pageBean.setTotalCount(totalCount);
//		} else {
//			list =hibernateTemplate.findByCriteria(detachedCriteria);
//		}
//		return new PageList<E>((List<E>)list, pageBean);
//	}
	
	// 
	
//	/**
//	 * 单对象查询
//
//	 * @param hql
//	 * @param objects
//	 * @return
//	 * 2014年3月21日 下午2:08:26
//	 
//	protected T queryForObject(final String hql, final Object ... objects){
//		PageList<E> pageList = this.queryForList(hql, null, null, objects);
//		if(pageList != null && pageList.isEmpty()){
//			return pageList.get(0);
//		}
//		return null;
//	}

	*//**
	* 执行查询结果集

	* @param hql
	* @param page
	* @param pageSize
	* @param objects
	* @return
	* 2014年3月21日 下午2:08:09
	*//*
//	protected PageList<E> queryForList(final String hql, final PageBean pageBean, final Object ... objects ){
//		return hibernateTemplate.execute(new HibernateCallback<PageList<E>>() {
//			@SuppressWarnings("unchecked")
//			@Override
//			public PageList<E> doInHibernate(Session session) throws HibernateException {
//				Query createQuery = createQuery(session, hql, objects);
//				List<E> list = null;
//				if(pageBean != null){
//					createQuery.setFirstResult(pageBean.getLimit());   
//					createQuery.setMaxResults(pageBean.getOffset());  
//					list = createQuery.list();
//					String countHql = null;
//					if(StringUtils.containsIgnoreCase(hql, "from")){
//						countHql = "select count(0) "+StringUtils.substring(hql, StringUtils.indexOfIgnoreCase(hql, "from"));
//					}
//					Query countQuery = createQuery(session, countHql, objects);
//					List<Long> countList = countQuery.list();
//					Long totalCount = 0L;
//					if(countList != null && countList.size() > 0){
//						totalCount =countList.get(0);
//					}
//					pageBean.setTotalCount(totalCount);;
//				} else {
//					list = createQuery.list();
//				}
//				return new PageList<E>(list, pageBean);
//			}
//			
//		});
//	}

	*//**
	* 执行查询以外的操作
	* @param hql
	* @param objs
	* 2014年3月21日 上午11:42:19
	*//*
	protected Integer executeUpdate(final String hql, final Object ... objects){
		return currentSession().execute(new HibernateCallback<Integer>() {
			public Integer doInHibernate(Session session) throws HibernateException {
				Query createQuery = createQuery(session, hql, objects);
				return createQuery.executeUpdate();
			}
		});
	}
	*//**
	* 得到泛型中的实体类型

	* @return
	* 2014年3月18日 下午2:32:35
	*//*
	protected Class<E> getEntityClass(){
		@SuppressWarnings("unchecked")
		Class<E> entityClass = (Class<E>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		return entityClass;
	}
	*//**
	* @Author: Charles
	* @Description: 获取表主键类型
	* @param clazz
	* @return Type:
	*//*
	public final Type getPkType() {
		ClassMetadata meta = currentSession().getSessionFactory().getClassMetadata(getEntityClass());
		return meta.getIdentifierType();
	}
	*//**
	* 获取主键名

	* @return
	* 2014年3月21日 下午2:42:49
	*//*
	public final String getPkColunmName(){
		ClassMetadata meta = currentSession().getSessionFactory().getClassMetadata(getEntityClass());
		return meta.getIdentifierPropertyName();
	}

*//**
	* 获取实体类型名

	* @return
	* 2014年3月18日 下午2:33:01
	*//*
	protected String getEntityClassName() {
		ClassMetadata meta = currentSession().getSessionFactory().getClassMetadata(getEntityClass());
		return meta.getEntityName();
	}
	*//**
	* 返回设置好参数的查询对象

	* @param query
	* @param objects
	* 2014年3月21日 下午2:07:56
	*//*
	private Query createQuery(Session session,String hql, Object ... objects) {
		Query query = session.createQuery(hql);
		if (objects != null){
			for (int i = 0; i < objects.length; i++) {
				query.setParameter(i, objects[i]);
			}
		}
		return query;
	}

	@SuppressWarnings("unchecked")
	public List<E> find(String hql, String[] paramNames, Object[] values) {
		List<E> ret = null;
		ret = (List<E>)currentSession().findByNamedParam(hql, paramNames,values);
		return ret;
	}

	@SuppressWarnings("unchecked")
	public List find(final String hql, final Map<String, Object> param, final int pageNo,
			final int pageSize) {
		return currentSession().execute(new HibernateCallback<List>() {
			public List doInHibernate(Session session) throws HibernateException {
				String shql=hql;
				if (pageNo == 0&&pageSize!=0) {
					String sql = "select count(e) ";
					shql = sql + hql;
				}
				Query query = session.createQuery(shql);
				if (param != null && param.size() > 0) {
					for (String property : param.keySet()) {
						if (param.get(property) instanceof List){
							query.setParameterList(property, (Collection)param.get(property));
						}else{
							query.setParameter(property,
									param.get(property));
						}
					}
				}
				if (pageNo != 0 && pageSize != 0) {
					query.setFirstResult((pageNo - 1) * pageSize);
					query.setMaxResults(pageSize);
				}
				List list = null;
				try{
					list = query.list();
				}catch (HibernateException e) {
					e.printStackTrace();
					throw e;
				}
				return list;
			}
		});
		
	}

@SuppressWarnings("unchecked")
	public final List<E> find(final String hql,final Map<String, Object> param) {
		Session session = currentSession().getSessionFactory().getCurrentSession();
		Query query = session.createQuery(hql);
		if (param != null && param.size() > 0) {
			for (String property : param.keySet()) {
				query.setParameter(property,param.get(property));
			}
		}
		return query.list();
		return hibernateTemplate.execute(new HibernateCallback<List>() {
			@Override
			public List<E> doInHibernate(Session session) throws HibernateException {
				Query query = session.createQuery(hql);
				if (param != null && param.size() > 0) {
					for (String property : param.keySet()) {
						query.setParameter(property,param.get(property));
					}
				}
				return query.list();
			}
		});

	}
//
//	@Override
//	public List<E> find(String hql) {
//		return this.queryForList(hql, null).getResultList();
//	}
//
//	@SuppressWarnings("unchecked")
//	@Override
//	public List findHql(String hql) {
//		return this.queryForList(hql, null).getResultList();
//	}

	@SuppressWarnings("unchecked")
	public final Object getById(Class c, Serializable id) {
		Object ret = currentSession().get(c, id);
		return ret;
	}

	public List findHql(final String hql, final Map<String, Object> param) {
		return currentSession().execute(new HibernateCallback<List>() {
			public List<E> doInHibernate(Session session) throws HibernateException {
				Query query = session.createQuery(hql);
				if (param != null && param.size() > 0) {
					for (String property : param.keySet()) {
						query.setParameter(property,param.get(property));
					}
				}
				return query.list();
			}
		});
	}

	public int updateHql(String hql) {
		return executeUpdate(hql, null);
	}
	public final List<E> find(String hql) {
		List<E> list = this.find(hql, null);
		return list;
	}

	public List findHql(String hql) {
			List list = findHql(hql, null);
			return list;
		}*/
}